import {CanActivate,ExecutionContext,Injectable,UnauthorizedException } from '@nestjs/common'
import {JwtService} from '@nestjs/jwt'
import { jwtConstants } from './constants'
import { Request } from 'express'

@Injectable()
export class AuthGuard implements CanActivate {
    constructor(private jwtService:JwtService){}

    async canActivate(context:ExecutionContext):Promise<boolean>{
        const request = context.switchToHttp().getRequest()
        const token = this.extractTokenFromHeader(request)
        if(!token){
            throw new UnauthorizedException()
        }
        try{
            const payload = await this.jwtService.verifyAsync(token,{
                secret:jwtConstants.secret
            })
            // 将 payload挂载在请求对象上，方便在路由处理器中访问
            request['user'] = payload
        } catch(e){
            throw new UnauthorizedException()
        }
        return true
    }

    private extractTokenFromHeader(request:Request):string | undefined{
        
        const [type,token] = request.headers.authorization?.split(' ') ?? []
        return type === 'Bearer' ? token : undefined
    }
}
